package com.bbx.taxi.client.Activity.Menu;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;

import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.base.BaseRequest;
import com.bbx.api.sdk.model.passanger.UserBuild;
import com.bbx.api.sdk.model.passanger.Return.Info;
import com.bbx.api.sdk.model.passanger.Return.RecommendCode;
import com.bbx.api.sdk.model.passanger.Return.User;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.passeger.conn.GetUserNet;
import com.bbx.api.sdk.net.passeger.conn.RecommendCodeNet;
import com.bbx.api.sdk.net.passeger.conn.SetUserNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.Main.MainActivity;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute;
import com.bbx.taxi.client.Bean.Extra.PersonalDataActivityMsg;
import com.bbx.taxi.client.Util.FormatUtil;
import com.bbx.taxi.client.emoji.MyConvertToMsg;
import com.bbx.taxi.client.widget.MaxByteLengthEditText;
import com.bbx.taxi.client.widget.CircleHead.CircleImageView;
import com.bbx.taxi.client.widget.SlidingCard2.DiscoverContainerView.OnFinish;
import com.bbx.taxi.client.widget.pop.UploadPhotosPopView;
import com.bbx.taxi.client.widget.pop.UploadPhotosPopView.OnPhotosPoPViewStateListener;

public class PersonalDataActivity extends BaseBBXActivity implements
		OnClickListener, OnPhotosPoPViewStateListener, TextWatcher {
	@Bind(R.id.headlayout)
	RelativeLayout headlayout;
	@Bind(R.id.head)
	CircleImageView head;
	@Bind(R.id.layout_name)
	RelativeLayout layout_name;
	@Bind(R.id.pop_background)
	View pop_background;
	@Bind(R.id.rb_man)
	RadioButton rb_man;
	@Bind(R.id.rb_girl)
	RadioButton rb_girl;
	@Bind(R.id.et_name)
	MaxByteLengthEditText et_name;
	@Bind(R.id.tv_phone)
	TextView tv_phone;
	@Bind(R.id.iv_delete)
	ImageView iv_delete;
	@Bind(R.id.tv_code)
	TextView tv_code;
	@Bind(R.id.layout_code)
	LinearLayout layout_code;
	private UploadPhotosPopView mUploadPhotosPopView;
	private UserTask mUserTask;
	/** 主界面的信息临时存储 */
	private MainAttribute main;
	public String sex_man = "1";
	public String sex_girl = "2";
	public RecommendCodeTask mRecommendCodeTask;
	public getUserTask mgetUserTask;
	//旧数据，用于判断数据是否有变化
	String oldname;
	String oldsex;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.personaldata);
		super.onCreate(savedInstanceState);
		
	}

	@Override
	protected void initView() {
		setTitle(true,getString(R.string.title_personal_data), -1, getString(R.string.title_right_save));
		// headlayout.setOnClickListener(this);
		// layout_name.setOnClickListener(this);
		mUploadPhotosPopView = new UploadPhotosPopView(this);
		mUploadPhotosPopView.setOnPhotosPoPViewStateListener(this);
		iv_delete.setOnClickListener(this);
		et_name.addTextChangedListener(this);
		if(loaddialog!=null&&!loaddialog.isShowing()){
			loaddialog.show();
		}
		getRecommendCode();
		setView();
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	public void setView() {
		if (mApplication.user_name.equals("")) {
			// et_name.setHint(getString(R.string.text_name));
		} else {
			et_name.setText(mApplication.user_name);
			et_name.setSelection(et_name.getText().length());
		}

		tv_phone.setText(FormatUtil.onFormatTelephone(mApplication.user_phone));
		String user_sex = SharedPreUtil.getStringValue(
				PersonalDataActivity.this, SharedPreEncryptUtil.user_sex,
				sex_man);
		if (user_sex.equals(sex_man)) {
			rb_man.setChecked(true);
			rb_girl.setChecked(false);
		} else if (user_sex.equals(sex_girl)) {
			rb_man.setChecked(false);
			rb_girl.setChecked(true);
		}
		tv_code.setText(SharedPreUtil.getStringValue(PersonalDataActivity.this, SharedPreEncryptUtil.user_code,""));
	}

	@Override
	protected void desotryItems() {
		// TODO Auto-generated method stub

	}

	public void getRecommendCode() {
		BaseRequest mBaseRequest = new BaseRequest(context);
		mBaseRequest.uid = mApplication.getUid();
		mBaseRequest.access_token = mApplication.getToken();
		mRecommendCodeTask = new RecommendCodeTask(context, mBaseRequest);
		mRecommendCodeTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	/**
	 * 获取用户消息
	 */
	public void getInfo() {
		UserBuild mUserBuild = new UserBuild(context);
		mUserBuild.uid = mApplication.getUid();
		mUserBuild.access_token = mApplication.getToken();
		mgetUserTask = new getUserTask(context, mUserBuild);
		mgetUserTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	/**
	 * 提交用户信息
	 */
	public void setInfo() {
		if(et_name.getText().toString().equals(oldname)&&( rb_man.isChecked() ? sex_man : sex_girl).equals(oldsex)){
			finish();
			return ;
		}
		if(loaddialog!=null&&!loaddialog.isShowing()){
			loaddialog.show();
		}
		UserBuild mUserBuild = new UserBuild(context);
		mUserBuild.uid = mApplication.getUid();
		mUserBuild.access_token = mApplication.getToken();
		Info info = new Info();
		info.user_name = new MyConvertToMsg().parseEmoji(context, et_name
				.getText().toString());
		info.sex = rb_man.isChecked() ? sex_man : sex_girl;
		mUserBuild.info = info;
		mUserTask = new UserTask(context, mUserBuild);
		mUserTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private class UserTask extends BaseAsyncTask {
		private UserBuild mUserBuild;
		private UserBuild user;

		public UserTask(Activity context, UserBuild mUserBuild) {
			super(context,false);
			this.mUserBuild = mUserBuild;
		}

		@Override
		public void onSuccess(int status,Object object) {
			if(loaddialog!=null){
				loaddialog.dismiss();
			}
			if (object != null) {
				ToastUtil.showToast(context, getString(R.string.submit_success));
				SharedPreUtil.putStringValue(PersonalDataActivity.this,
						SharedPreEncryptUtil.user_name, et_name.getText()
								.toString());
				SharedPreUtil.putStringValue(PersonalDataActivity.this,
						SharedPreEncryptUtil.user_sex,
						rb_man.isChecked() ? sex_man : sex_girl);
				main = MainAttribute.getInstance();
				if (mApplication.user_name.equals(main.getName())) {// 如果相同，则要更改主界面的“本人改成名字”
					main.setName(et_name.getText().toString());
				} else {

				}
				mApplication.user_name = et_name.getText().toString();
				onfinish();
			} else {
				ToastUtil.showToast(context,getString(R.string.submit_fail));
			}

		}

		@Override
		public void onFailed(int status, String msg) {
			// TODO Auto-generated method stub
			ToastUtil.showToast(context,
					getResources().getString(R.string.no_network));
			if(loaddialog!=null){
				loaddialog.onDismiss();
			}
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mUserBuild).getJson();
			return new SetUserNet(context, json);
		}

	}
    public void onfinish(){
    	Intent intent = new Intent();
		intent.putExtra(PersonalDataActivityMsg.NAME, et_name.getText().toString());
		setResult(PersonalDataActivityMsg.requestCode, intent);
		super.finish();
    }
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_right:// 保存
			if (et_name.getText().toString().equals("")
					|| et_name.getText().toString().replaceAll(" ", "")
							.equals("")) {
				ToastUtil.showToast(context, R.string.name_no_empty);
				return;
			}
			setInfo();
			break;
		case R.id.layout_name:
			// startActivityForResult(
			// new Intent(this, EditNameActivity.class).putExtra(
			// "user_name", et_name.getText().toString()),
			// MainAttribute.REQUEST_CODE_EDITNAME);
			break;
		case R.id.headlayout:
			mUploadPhotosPopView.onShow(v);
			break;
		case R.id.iv_delete:
			et_name.setText("");
			break;
		default:
			super.onClick(v);
			break;
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		mUploadPhotosPopView.onDismiss();
		ContentResolver resolver = getContentResolver();
		byte[] mContent;
		Bitmap myBitmap;
		switch (requestCode) {
		case 0:
			mUploadPhotosPopView.cropImageUri(
					Uri.fromFile(UploadPhotosPopView.sdcardTempFile), 2);
			break;
		case 1:
			Uri originalUri = data.getData();
			mUploadPhotosPopView.cropImageUri(originalUri, 2);
			break;
		case 2:
			Bitmap bm = BitmapFactory
					.decodeFile(UploadPhotosPopView.sdcardTempFile
							.getAbsolutePath() + "tmp");
			head.setImageBitmap(bm);

			break;
		case MainAttribute.REQUEST_CODE_EDITNAME:
			if (data != null) {
				et_name.setText(data.getStringExtra("user_name"));
				et_name.setSelection(et_name.getText().length());
			}
			break;
		}
	}

	@Override
	public void onPhotosPopViewState(boolean isOpen) {
		if (isOpen) {
			pop_background.setVisibility(View.VISIBLE);
		} else {
			pop_background.setVisibility(View.GONE);
		}
	}

	protected void onDestroy() {
		if (mUserTask != null
				&& mUserTask.getStatus() != AsyncTask.Status.FINISHED)
			mUserTask.cancel(true);
		if (mRecommendCodeTask != null
				&& mRecommendCodeTask.getStatus() != AsyncTask.Status.FINISHED)
			mRecommendCodeTask.cancel(true);
		if (mgetUserTask != null
				&& mgetUserTask.getStatus() != AsyncTask.Status.FINISHED)
			mgetUserTask.cancel(true);
		super.onDestroy();

	}

	int index = 0;

	@Override
	public void afterTextChanged(Editable s) {
		if (!s.toString().isEmpty()) {
			iv_delete.setVisibility(View.VISIBLE);

		} else {
			iv_delete.setVisibility(View.GONE);
		}
 		if (s.toString().contains(" ")) {
			et_name.removeTextChangedListener(this);
			index = et_name.getSelectionStart();
			et_name.setText(s.toString().replaceAll(" ", ""));
			et_name.setSelection(index-1);
			et_name.addTextChangedListener(this);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub

	}

	private class RecommendCodeTask extends BaseAsyncTask {
		BaseRequest mBaseRequest;

		public RecommendCodeTask(Activity context, BaseRequest mBaseRequest) {
			super(context,false);
			this.mBaseRequest = mBaseRequest;
		}

		@Override
		public void onSuccess(int status,Object object) {
			// TODO Auto-generated method stub
			if (object != null) {
				RecommendCode mRecommendCode = (RecommendCode) object;
				if (mRecommendCode.getDetail() != null
						&& mRecommendCode.getDetail().getRecommend_code() != null) {
					tv_code.setText(mRecommendCode.getDetail()
							.getRecommend_code());
					SharedPreUtil.putStringValue(PersonalDataActivity.this,
							SharedPreEncryptUtil.user_code,tv_code.getText().toString());
				}
			} else {
				ToastUtil.showToast(context,
						getResources().getString(R.string.no_network));
			}
			getInfo();
		}

		@Override
		public void onFailed(int status, String msg) {
			if(loaddialog!=null){
				loaddialog.onDismiss();
			}
			ToastUtil.showToast(context, R.string.no_network);
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mBaseRequest).getJson();
			return new RecommendCodeNet(context, json);
		}
	}

	private class getUserTask extends BaseAsyncTask {
		private UserBuild mUserBuild;
		private UserBuild user;

		public getUserTask(Activity context, UserBuild mUserBuild) {
			super(context,false);
			this.mUserBuild = mUserBuild;
		}

		@Override
		public void onSuccess(int status,Object object) {
			// TODO Auto-generated method stub
			if (object != null) {
				User user = (User) object;
				Info info = user.info;
				mApplication.user_name = info.user_name;
				mApplication.user_phone = info.phone;
				mApplication.user_sex = info.sex;
				oldname=info.user_name;
				oldsex=info.sex;
				SharedPreUtil.putStringValue(context,
						SharedPreEncryptUtil.user_name, mApplication.user_name);
				SharedPreUtil.putStringValue(context,
						SharedPreEncryptUtil.user_sex, mApplication.user_sex);
				if (main != null) {
					main.setName(mApplication.user_name);
					main.setTel(mApplication.user_phone);
				}
				setView();
			} else {
			}
			if(loaddialog!=null){
				loaddialog.onDismiss();
			}
		}

		@Override
		public void onFailed(int status, String msg) {
			if(loaddialog!=null){
				loaddialog.onDismiss();
			}
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mUserBuild).getJson();
			return new GetUserNet(context, json);
		}

	}
}
